<template>
  <div class="user-list">
    <!-- 添加顶部栏 -->
    <div class="header-bar">
      <h2>用户管理</h2>
      <div class="user-info">
        <span>欢迎您，{{ currentUser.userName }}</span>
        <el-button type="danger" link @click="handleLogout">
          <el-icon><SwitchButton /></el-icon>退出登录
        </el-button>
      </div>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <div class="left">
        <el-input
          v-model="searchText"
          placeholder="请输入用户名搜索"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>搜索
        </el-button>
      </div>
      
      <el-button 
        type="success" 
        @click="handleAdd"
        v-if="currentUser.role === 'admin'">
        <el-icon><Plus /></el-icon>新增用户
      </el-button>
    </div>

    <!-- 用户表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="userId" label="用户ID" width="180" align="center" />
        <el-table-column prop="userName" label="用户名" min-width="150" align="center" />
        <el-table-column prop="role" label="角色" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'success'" effect="plain">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              @click="handleEdit(scope.row)"
              v-if="currentUser.role === 'admin' || currentUser.userId === scope.row.userId">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-popconfirm
              title="确定删除该用户吗？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleDelete(scope.row)"
              v-if="currentUser.role === 'admin' && currentUser.userId !== scope.row.userId">
              <template #reference>
                <el-button type="danger" link>
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
      destroy-on-close
      @close="resetForm">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
        class="dialog-form">
        <el-form-item label="用户ID" prop="userId" v-if="dialogType === 'add'">
          <el-input v-model="formData.userId" placeholder="请输入用户ID" clearable />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item 
          label="密码" 
          prop="password"
          :rules="dialogType === 'add' ? rules.password : rules.editPassword">
          <el-input 
            v-model="formData.password" 
            type="password" 
            placeholder="请输入密码"
            show-password />
          <div class="tip-text" v-if="dialogType === 'edit'">
            不修改密码请留空
          </div>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="formData.role" placeholder="请选择角色" class="full-width">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Edit, Delete, SwitchButton } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { get, post } from '@/api/api'

const router = useRouter()

// 表格数据
const tableData = ref([])
const loading = ref(false)
const submitLoading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索
const searchText = ref('')

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

// 表单数据
const formData = reactive({
  userId: '',
  userName: '',
  password: '',
  role: 'user'
})

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))

// 表单验证规则
const rules = {
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  editPassword: [
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await get('/user/user/page', {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      search: searchText.value
    })
    
    console.log('API返回数据:', res)
    
    // 直接判断 res.data 中的数据
    if (res.data && Array.isArray(res.data.records)) {
      tableData.value = res.data.records
      total.value = res.data.total || 0
      console.log('设置后的表格数据:', tableData.value)
    } else {
      console.error('返回数据格式不正确:', res.data)
      ElMessage.error('数据格式不正确')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

// 添加用户
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm()
}

// 编辑用户
const handleEdit = (row) => {
  // 检查权限：只有管理员可以编辑所有用户，普通用户只能修改自己的信息
  if (currentUser.value.role !== 'admin' && currentUser.value.userId !== row.userId) {
    ElMessage.warning('您没有权限修改其他用户的信息')
    return
  }

  dialogType.value = 'edit'
  dialogVisible.value = true
  const { password, ...rest } = row
  Object.assign(formData, rest)
  formData.password = '' // 清空密码字段
}

// 删除用户
const handleDelete = async (row) => {
  // 检查权限：只有管理员可以删除用户
  if (currentUser.value.role !== 'admin') {
    ElMessage.warning('只有管理员可以删除用户')
    return
  }

  // 不能删除自己
  if (row.userId === currentUser.value.userId) {
    ElMessage.warning('不能删除当前登录用户')
    return
  }

  try {
    await post('/user/user/delete', { userId: row.userId })
    ElMessage.success('删除成功')
    if (tableData.value.length === 1 && currentPage.value > 1) {
      currentPage.value--
    }
    fetchUsers()
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const url = dialogType.value === 'add' ? '/user/user/register' : '/user/user/update'
        
        // 构建提交数据
        const submitData = {
          userId: formData.userId,
          userName: formData.userName,
          role: formData.role
        }
        
        // 如果是新增或者编辑时修改了密码，则添加密码字段
        if (dialogType.value === 'add' || formData.password) {
          submitData.password = formData.password
        }
        
        await post(url, submitData)  // 统一使用 POST 请求
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
        fetchUsers()
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加失败:' : '更新失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.userId = ''
  formData.userName = ''
  formData.password = ''
  formData.role = 'user'
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('user')
  localStorage.removeItem('token')
  router.push('/login')
  ElMessage.success('已退出登录')
}

// 初始化
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-list {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
  height: 60px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.header-bar h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info span {
  color: #606266;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-bar .left {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.table-card :deep(.el-card__body) {
  padding: 0;
}

.pagination {
  margin-top: 20px;
  padding: 15px;
  display: flex;
  justify-content: flex-end;
  background: #fff;
  border-top: 1px solid #ebeef5;
}

.dialog-form {
  padding: 20px 20px 0;
}

.dialog-footer {
  padding: 20px 0 10px;
  text-align: right;
}

.tip-text {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.2;
}

.full-width {
  width: 100%;
}

:deep(.el-table) {
  border-radius: 8px 8px 0 0;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-tag) {
  min-width: 80px;
}
</style>
